'use strict';

const BaseService = require('../base');
const axios = require('axios');
const wxConfig = require("../../../config/wx");
class QrcodeService extends BaseService {
  static get modelName() {
    return 'Common.Qrcode';
  }
  
  async getQrcode(url) {
    try {
      const tokenRes = await this.ctx.curl(`https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${wxConfig.appid}&secret=${wxConfig.secret}`, { method: 'GET', dataType: 'json' });
      const token = tokenRes.data.access_token
      if (tokenRes.data.errcode) {
        throw new Error(tokenRes.data.errmsg);
      }
      const requestData = {
        path: url,
        width: 430,
        env_version: 'trial'
      }
      const qcodeRes = await axios({
        url: `https://api.weixin.qq.com/wxa/getwxacode?access_token=${token}`,
        method: 'POST',
        data: requestData,
        responseType: 'arraybuffer',
      });
      const result = await this.ctx.service.common.upload.uploadCos(qcodeRes.data, new Date().getTime() + '.jpg')

      return 'https://' + result.Location
    }
    catch (e) {
      console.log('e', e);
      throw new Error(e);
    }
  }
}

module.exports = QrcodeService;
